<template>
  <el-form
      ref="loginRefForm"
      :model="loginForm"
      :rules="rules"
      label-width="auto"
      :label-position="labelPosition"
      :size="size"
  >
    <el-form-item label="账号" prop="userName">
      <el-input type="text" v-model="loginForm.userName" placeholder="请输入账号"/>
    </el-form-item>
    <el-form-item label="密码" prop="passWord">
      <el-input type="password" v-model="loginForm.passWord" placeholder="请输入密码"/>
    </el-form-item>
    <div style="width:100%" class="myFlex-x">
      <el-form-item>
        <el-button type="primary" @click="submitForm">立即登录</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </div>
  </el-form>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue';
import {ElMessage} from "element-plus";
import request from "@/utils/request";
import {useUserStore} from "@/stores/useUserStore";
import {id} from "element-plus/es/locale";
const userStore = useUserStore();
//接受父组件传来的函数
const emit=defineEmits(['close-dialog'])
const loginRefForm = ref();
const loginForm = ref({
  userName: '',
  passWord: ''
});
const rules={
  userName:[
      { required: true, message: '请输入账号', trigger: 'blur' },
      { pattern: /^[a-zA-Z0-9_-]{4,12}$/,message: '账号必须由英文字母5-12位组成',trigger: 'blur' }
  ],
  passWord:[
  { required: true, message: '请输入密码', trigger: 'blur' },
  { pattern: /^[a-zA-Z0-9_-]{4,12}$/,message: '密码必须由英文字母5-12位组成',trigger: 'blur' }
]
}
const size = ref('large');
const labelPosition = ref('left');

const onSubmit = () => {
  console.log('提交:', loginForm);
};
//点击重置
function resetForm() {
  loginRefForm.value.resetFields();
}
//点击登录
function submitForm() {
  loginRefForm.value.validate(valid => {
    if (valid) {
      //发送登录请求时是将用户输入的账号和密码传输给后端，然后后端校验完毕响应给前端
      request.get("/login",{params:loginForm.value})
      .then(res=>{
        if(res.data!=null){
          ElMessage.success('登录成功')
          emit('close-dialog')
          //登录成功之后，将用户信息保存到用户状态当中，状态组件时pinia组件
          userStore.$patch({
            userName: res.data.userName,
            id: res.data.id
          });

        }else {
          ElMessage.error('登录失败')
        }
      })//访问后端成功的回调
      .catch(err=>{
        ElMessage.error(err.message)
      })//失败的回调
    } else {
      ElMessage.error('登录失败')
    }
  });
}

</script>

<style scoped>

</style>